package com.dkd.day20250616;

import java.util.ArrayList;

public class SolutionlowestCommonAncestor {
    public static void main(String[] args) {

    }
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param p int整型
     * @param q int整型
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        //思路，获得路径，然后比较
        ArrayList<Integer> listp = getPath(root, p);
        ArrayList<Integer> listq = getPath(root, q);
        int res = 0;
        for (int i = 0; i < listp.size() && i<listq.size(); i++) {
            int a = listp.get(i);
            int b = listq.get(i);
            if(a == b){
                res =a;
            }else break;

        }
        return res;
    }

    public ArrayList<Integer> getPath (TreeNode root, int target) {
        ArrayList<Integer> path = new ArrayList<>();
        if (root == null) return path;
        while (root != null) {
            path.add(root.val);
            if (root.val < target) {
                root = root.right;
            }
            else if (root.val > target) {
                root = root.left;
            }else{
                return path;
            }
        }
        return path;
    }
}
